/**   
 * @Title: OnlineCompiler.java 
 * @Package: com.rename.icode.model 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-4-17 上午10:09:44 
 * @version  
 */

package com.rename.icode.model;

import android.content.Intent;
import android.net.ParseException;

import com.rename.icode.comm.ApplicationContext;
import com.rename.icode.comm.Constants;
import com.rename.icode.manager.UserManager;
import com.rename.icode.utils.HttpURLTools;
import com.rename.icode.utils.LogUtil;
import com.rename.icode.utils.StringUtil;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 实现了...功能
 * @author Administrator
 * @date 2015-4-17 上午10:09:44
 * @version V1.0
 */

public class OnlineCompiler implements ICompiler {
	
	private static final String TAG = "OnlineCompiler";
	private String result = null;

	public OnlineCompiler() {

	}

	static class Loader {
		static final OnlineCompiler INSTANCE = new OnlineCompiler();
	}

	public static OnlineCompiler getInstance() {
		return Loader.INSTANCE;
	}

	/**
	 * Description
	 * 
	 * @param filePath
	 * @return
	 * @see com.rename.icode.model.ICompiler#compile(java.lang.String)
	 */

	@Override
	public Object compile(CodeFile codeFile) {
		String sdDir = codeFile.getPath().replaceAll(codeFile.getName(), "");
		String username = UserManager.getInstance().getUser().getName();

		LogUtil.i(TAG, "sdPath is " + sdDir);
		
		if(!Constants.CODE_SERVER_DIR.equals(sdDir)){
			/*
			 * 如果是本地SD卡中的文件，首先上传文件，再发送文件名+用户名请求文件上传到服务器，得到代码编译后的结果
			 */
			result = HttpURLTools.postFile(Constants.UPLOAD_URL,
					codeFile.getPath(), username);
			if (StringUtil.empty(result)
					|| Constants.UPLOAD_FAIL.equals(result)) {
				LogUtil.i(TAG, "文件上传失败");
				return null;
			} 
			LogUtil.i(TAG, "上传文件返回结果：" + result);
			UserManager.getInstance().refreshSeverData(); // 文件上传完成，刷新服务器文件列表
			// ServerFragment界面刷新通知
			Intent serverIntent = new Intent();
			serverIntent.setAction(Constants.SERVER_REFRESH);
			ApplicationContext.get().sendBroadcast(serverIntent);
			LogUtil.i(TAG, "SERVER_REFRESH广播发送完毕...");
		}

		// 如果是服务器文件或者文件已上传，文件名+用户名请求， 发送文件编译请求
		Map<String, String> params = new HashMap<String, String>();
		params.put("userinfo", username);
		params.put("codename", codeFile.getName());
		HttpResponse response = HttpURLTools.sendHttpPost(
				Constants.COMPILER_URL, params);

		if (null != response) {
			try {
				result = EntityUtils.toString(response.getEntity());
				LogUtil.i(TAG, "编译文件返回结果：" + result);
			} catch (ParseException | IOException e) {
				e.printStackTrace();
			}
		} else {
			result = null;
		}
		return result;
	}

}
